package store.aixx.jwt.demo.security.filter;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import store.aixx.jwt.demo.security.handler.TokenHandler;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author yukai
 * @since 2021年12月11日 0:32
 */
@Slf4j
public class MyAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    private final ObjectMapper objectMapper = new ObjectMapper();

    protected TokenHandler tokenHandler;


    public void setTokenHandler(TokenHandler tokenHandler) {
        this.tokenHandler = tokenHandler;
    }



    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {

        UsernamePasswordAuthenticationToken authRequest = null;
        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        } else {
            try {
                ServletInputStream inputStream = request.getInputStream();
                JsonNode jsonNode = objectMapper.readTree(inputStream);
                String username = jsonNode.get(this.getUsernameParameter()).textValue();
                String password = jsonNode.get(this.getPasswordParameter()).textValue();
                authRequest = new UsernamePasswordAuthenticationToken(username, password);
                this.setDetails(request, authRequest);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return this.getAuthenticationManager().authenticate(authRequest);
        }
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        tokenHandler.generatorToken(request, response, authResult);
    }
}
